package org.lingshi.shopping_admin_srevice.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.lingshi.common.entity.Role;
import org.lingshi.common.entity.RolePermission;
import org.lingshi.common.service.IRoleService;
import org.lingshi.shopping_admin_srevice.mapper.RoleMapper;
import org.lingshi.shopping_admin_srevice.mapper.RolePermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;

@DubboService
public class RoleServiceImpl implements IRoleService {
    
     @Autowired
     private RoleMapper roleMapper;

     @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    /**
     * 新增
     *
     * @param role
     */
    @Override
    public void add(Role role) {
        roleMapper.insert(role);
    }

    /**
     * 删除
     *
     * @param rid
     */
    @Override
    public void delete(Long rid) {
        roleMapper.deleteById(rid);
        LambdaUpdateWrapper<RolePermission> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RolePermission::getRid,rid);
        rolePermissionMapper.delete(updateWrapper);
    }

    /**
     * 修改
     *
     * @param role
     */
    @Override
    public void update(Role role) {
        roleMapper.updateById(role);
    }

    /**
     * 根据id查找
     *
     * @param rid
     * @return
     */
    @Override
    public Role findById(Long rid) {
        Role role = roleMapper.findById(rid);
        return role;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Role> search(int page, int size) {
        return roleMapper.selectPage(new Page<>(page,size),null);
    }

    /**
     * 修改权限
     *
     * @param rid
     * @param pids
     */
    @Override
    public void updatePermissionToRole(Long rid, Long[] pids) {
        LambdaUpdateWrapper<RolePermission> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RolePermission::getRid,rid);
        rolePermissionMapper.delete(updateWrapper);

        for (Long pid : pids) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRid(rid);
            rolePermission.setPid(pid);
            rolePermissionMapper.insert(rolePermission);
        }
    }
}
